package net.xo68.destiny.starter.worker.logger;

import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.common.SystemConstants;
import net.xo68.destiny.contract.domain.logger.LoggerInfo;
import net.xo68.destiny.core.util.TimeUtils;
import net.xo68.destiny.starter.worker.SchedulerWorkerProperties;
import org.springframework.stereotype.Component;

import java.io.*;
import java.time.LocalDateTime;

/**
 * 任务日志读取
 * @author wuxie
 * @version 2020-11-4
 */
@Slf4j
@Component
public class JobLoggerReader {

    private final SchedulerWorkerProperties schedulerWorkerProperties;
    private final JobLoggerIndex jobLoggerIndex;

    public JobLoggerReader(SchedulerWorkerProperties schedulerWorkerProperties, JobLoggerIndex jobLoggerIndex) {
        this.schedulerWorkerProperties = schedulerWorkerProperties;
        this.jobLoggerIndex = jobLoggerIndex;
    }

    /**
     * 读取任务实例执行日志
     * @param jobInstanceId
     * @param beginLine
     * @return
     */
    public LoggerInfo readLogger(long jobInstanceId, int beginLine){

        Long dayIndex=jobLoggerIndex.getDayIndex(jobInstanceId);
        LocalDateTime localDateTime= TimeUtils.ofLocalDateTime(dayIndex*TimeUtils.DAY_MILLI);
        String folder=TimeUtils.toString(localDateTime,"yyyy-MM-dd");
        File loggerFolder=new File(this.schedulerWorkerProperties.loggerPath(),folder);
        if (!loggerFolder.exists()) {
            return new LoggerInfo(beginLine, 0, "readLog fail, logFile not exists", true);
        }
        File loggerFile=new File(loggerFolder,
                String.valueOf(jobInstanceId)+this.schedulerWorkerProperties.getLoggerSuffix());

        if (!loggerFile.exists()) {
            return new LoggerInfo(beginLine, 0, "readLog fail, logFile not exists", true);
        }

        // read file
        StringBuffer logContentBuffer = new StringBuffer();
        int toLineNum = 0;
        LineNumberReader reader = null;
        try {
            //reader = new LineNumberReader(new FileReader(logFile));
            reader = new LineNumberReader(new InputStreamReader(new FileInputStream(loggerFile), SystemConstants.ENCODE_DEFAULT));
            String line;

            while ((line = reader.readLine())!=null) {
                toLineNum = reader.getLineNumber();		// [from, to], start as 1
                if (toLineNum >= beginLine) {
                    logContentBuffer.append(line).append("\n");
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

        // result
        LoggerInfo logResult = new LoggerInfo(beginLine, toLineNum, logContentBuffer.toString(), false);
        return logResult;
    }
}
